package com.zpl.order.controller;

import com.alibaba.fastjson.JSON;
//import com.alipay.api.AlipayApiException;
//import com.alipay.api.AlipayClient;
//import com.alipay.api.DefaultAlipayClient;
//import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zpl.core.Result;
import com.zpl.order.config.AlipayConfig;
import com.zpl.order.entity.*;
import com.zpl.order.entity.dto.OrderAllKeyWordDTO;
import com.zpl.order.entity.dto.OrderKeyWordDTO;
import com.zpl.order.entity.vo.GAAll;
import com.zpl.order.entity.vo.OrderAllVO;
import com.zpl.order.enums.OrderStatus;
import com.zpl.order.feign.GoodsFeign;
import com.zpl.order.service.AddressService;
import com.zpl.order.service.CartService;
import com.zpl.order.service.OrderDetailsService;
import com.zpl.order.service.OrderService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;


@RestController
@RequestMapping("/order")
@Api(value = "OrderController", tags = {"订单管理"})
public class OrderController {
    @Resource
    private OrderService orderService;

    @Resource
    private OrderDetailsService orderDetailsService;

    @Resource
    private AddressService addressService;

    @Resource
    private CartService cartService;

    @Resource
    private GoodsFeign goodsFeign;

    @Autowired
    private AlipayConfig alipayConfig;

    @ApiOperation(value = "1、添加订单信息", notes = "添加订单及细节信息", httpMethod = "POST")
    @ApiImplicitParam(name = "order", value = "订单信息", dataType = "Order",required = true)
    @PostMapping
    public Result insert(@RequestBody Order order) {

//        redisCacheTemplate.opsForValue().set("user:", user);
//        User user1 = (User) redisCacheTemplate.opsForValue().get("user:");

//        Long memberId = 1308242661102137346L;

        List<Cart> list = cartService.selectByChecked(order.getMemberId());
//        order.setMemberId(memberId);
        if (orderService.insert(order)==false) {
            return Result.fail("订单生成失败");
        }

        //等待商品模块的方法完善
        for(int i=0;i<list.size();i++){
            OrderDetails orderDetails = new OrderDetails();
            System.out.println(order.getId());
            orderDetails.setOrderId(order.getId());
            orderDetails.setProductId(list.get(i).getGoodId());
            orderDetails.setProductCnt(list.get(i).getGoodNum());
            Goods goods = goodsFeign.getGoodFeign(list.get(i).getGoodId());
            orderDetails.setProductName(goods.getTitle());
            orderDetails.setProductPrice(goods.getNowPrice());
            if(orderDetailsService.insert(orderDetails)==false){
                return Result.fail("添加失败"+i);
            }
        }

        return Result.success("订单添加成功");
    }

    @ApiOperation(value = "2、删除订单信息", notes = "删除订单信息", httpMethod = "DELETE")
    @ApiImplicitParam(name = "id", value = "id", dataType = "int",required = true)
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable("id") Long id) {
        if (orderService.delete(id)) {
            return Result.success("删除成功");
        }
        return Result.fail("删除失败");
    }

    @ApiOperation(value = "3、修改订单信息", notes = "修改订单信息", httpMethod = "PUT")
    @ApiImplicitParam(name = "order", value = "订单信息", dataType = "Order",required = true)
    @PutMapping
    public Result update(@RequestBody Order order) {
        if (orderService.update(order)) {
            return Result.success("修改成功");
        }
        return Result.fail("修改失败");
    }

    @ApiOperation(value = "4、获取订单信息", notes = "按用户id获取订单信息", httpMethod = "GET")
    @ApiImplicitParam(name = "orderKeyWordDTO", value = "订单分页信息", dataType = "OrderKeyWordDTO",required = true)
    @PostMapping("/list")
    public Result getOrderByMemberId(@RequestBody OrderKeyWordDTO orderKeyWordDTO) {
//        Long memberId = 0L;//等其他模块完成后再加
        IPage<Order> page = orderService.selectByMemberId(orderKeyWordDTO);
        return Result.success(page);
    }

    @ApiOperation(value = "4、获取所有订单详细信息", notes = "获取所有订单详细信息", httpMethod = "GET")
    @ApiImplicitParam(name = "orderAllKeyWordDTO", value = "订单所有信息分页信息", dataType = "OrderAllKeyWordDTO",required = true)
    @PostMapping("/allinfolist")
    public Result getAllInfo(@RequestBody OrderAllKeyWordDTO orderAllKeyWordDTO) {
        System.out.println(JSON.toJSON(orderAllKeyWordDTO));
        IPage<OrderAllVO> page = orderService.getOrderAllList(orderAllKeyWordDTO);
        List<GAAll> list = new ArrayList<>();
        for(int i=0;i<page.getRecords().size();i++){
            GAAll gaAll = new GAAll();
            gaAll.setId(page.getRecords().get(i).getId());
            gaAll.setUpdateDate(page.getRecords().get(i).getUpdateDate());
            gaAll.setOperatorId(page.getRecords().get(i).getOperatorId());
            gaAll.setCreateDate(page.getRecords().get(i).getCreateDate());
            gaAll.setWId(page.getRecords().get(i).getWId());
            gaAll.setShippingUser(page.getRecords().get(i).getShippingUser());
            gaAll.setShippingTime(page.getRecords().get(i).getShippingTime());
            gaAll.setShippingSn(page.getRecords().get(i).getShippingSn());
            gaAll.setShippingMoney(page.getRecords().get(i).getShippingMoney());
            gaAll.setShippingCompName(page.getRecords().get(i).getShippingCompName());
            gaAll.setReceiveTime(page.getRecords().get(i).getReceiveTime());
            gaAll.setProductPrice(page.getRecords().get(i).getProductPrice());
            gaAll.setProductName(page.getRecords().get(i).getProductName());
            gaAll.setProductId(page.getRecords().get(i).getProductId());
            gaAll.setProductCnt(page.getRecords().get(i).getProductCnt());
            gaAll.setPayTime(page.getRecords().get(i).getPayTime());
            gaAll.setPaymentMoney(page.getRecords().get(i).getPaymentMoney());
            gaAll.setPaymentMethod(page.getRecords().get(i).getPaymentMethod());
            gaAll.setOrderTime(page.getRecords().get(i).getOrderTime());
            gaAll.setOrderStatus(page.getRecords().get(i).getOrderStatus());
            gaAll.setOrderPoint(page.getRecords().get(i).getOrderPoint());
            gaAll.setOrderMoney(page.getRecords().get(i).getOrderMoney());
            gaAll.setOrderId(page.getRecords().get(i).getOrderId());
            gaAll.setMemberId(page.getRecords().get(i).getMemberId());
            gaAll.setDeleteStatus(page.getRecords().get(i).getDeleteStatus());
            gaAll.setInvoiceTime(page.getRecords().get(i).getInvoiceTime());
            gaAll.setFeeMoney(page.getRecords().get(i).getFeeMoney());
            gaAll.setDistrictMoney(page.getRecords().get(i).getDistrictMoney());
            gaAll.setAverageCost(page.getRecords().get(i).getAverageCost());
            gaAll.setAddressId(page.getRecords().get(i).getAddressId());
            Goods goods = goodsFeign.getGoodFeign(page.getRecords().get(i).getProductId());
            gaAll.setOriginalPrice(goods.getOriginalPrice());
            gaAll.setNowPrice(goods.getNowPrice());
            gaAll.setMainImage(goods.getMainImage());
            Address address = addressService.selectById(page.getRecords().get(i).getAddressId());
            gaAll.setReceiverZip(address.getReceiverZip());
            gaAll.setReceiverProvince(address.getReceiverProvince());
            gaAll.setReceiverName(address.getReceiverName());
            gaAll.setReceiverMobile(address.getReceiverMobile());
            gaAll.setReceiverDistrict(address.getReceiverDistrict());
            gaAll.setReceiverCity(address.getReceiverCity());
            list.add(gaAll);
        }
        IPage<GAAll> iPage=new Page<>();
        iPage.setCurrent(page.getCurrent());
        iPage.setPages(page.getPages());
        iPage.setSize(page.getSize());
        iPage.setTotal(page.getTotal());
        iPage.setRecords(list);
        return Result.success(iPage);
    }


    @ApiOperation(value = "5、支付宝沙箱", notes = "支付宝沙箱", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "订单号", dataType = "Long",required = true)
    @RequestMapping("/payByAli/{id}")
    public void payController(@PathVariable Long id, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        Order order = orderService.selectById(id);//#
        AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig.getOpenApiDomain(), alipayConfig.getAppId(),
                alipayConfig.getMerchantPrivateKey(), alipayConfig.getFormat(), alipayConfig.getCharset(),
                alipayConfig.getAlipayPublicKey(), alipayConfig.getSignType()); // 获得初始化的AlipayClient
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
        alipayRequest.setReturnUrl(alipayConfig.getReturnUrl());
        alipayRequest.setNotifyUrl(alipayConfig.getNotifyUrl());// 在公共参数中设置回跳和通知地址
        alipayRequest.setBizContent("{" + "    \"out_trade_no\":\"" + id + "\","
                + "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + "    \"total_amount\":\""
                + order.getPaymentMoney() + "\"," + "    \"subject\":\"" + "欢迎使用甄漂亮商城" + "\","
                + "    \"body\":\"" + "遇到问题，客服7*24为你解答问题" + "\","
                + "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
                + "    \"extend_params\":{" + "    \"sys_service_provider_id\":\"2088511833207846\"" + "    }" + "  }");// 填充业务参数
        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=" + alipayConfig.getCharset());
        response.getWriter().write(form);// 直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @ApiOperation(value = "7、支付宝沙箱回调", notes = "支付宝沙箱回调", httpMethod = "GET")
    @ApiImplicitParam(name = "out_trade_no", value = "交易号", dataType = "number",required = true)
    @RequestMapping("/pay/return")
    public void  paySuccess(Long out_trade_no,HttpServletResponse response,HttpServletRequest request) throws Exception{
        Map<String, String> map = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = iter.next();
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            map.put(name, valueStr);
        }
        Order order = orderService.selectById(out_trade_no);


        boolean signVerified = false;
        try {
            signVerified = AlipaySignature.rsaCheckV1(map, alipayConfig.getAlipayPublicKey(),
                    alipayConfig.getCharset(), alipayConfig.getSignType());
        } catch (com.alipay.api.AlipayApiException e) {
            e.printStackTrace();
            System.out.println("支付宝回调异常");
            response.sendRedirect("/rlg/payFail.html");
        }
        if (signVerified) {
            order.setOrderStatus(OrderStatus.ZHI);
            orderService.update(order);
            List<OrderDetails> list = orderDetailsService.selectByOrderId(order.getId());
            for(int i = 0;i<list.size();i++){
                OrderDetails orderDetails = list.get(i);
                Goods goods = goodsFeign.getGoodFeign(orderDetails.getProductId());
                int sum = goods.getPlatinum()+orderDetails.getProductCnt();
                System.out.println(sum);
                goods.setPlatinum(sum);
                goodsFeign.update(goods);
            }
            response.sendRedirect("http://localhost:8080/order");
        } else {
            System.out.println("验证失败");
            response.sendRedirect("http://localhost:8080/order");
        }
    }


//    @PostMapping("pay")
//    public  Result Pay(@RequestBody Order order){
//
//        return null;
//    }
//    public void Pay(HttpServletRequest request,HttpServletResponse response,@RequestBody Order order) {
////        User user = (User) session.getAttribute("user"); //获取用户
//        //乱码处理
////        try {
////            request.setCharacterEncoding("UTF-8");
////            response.setContentType("text/html;charset=utf-8");//+AlipayConfig.charset
////        } catch (UnsupportedEncodingException e) {
////            e.printStackTrace();
////        }
//        //查看用户是否登陆-未登录自动跳转到登陆界面
////        if(user==null)
////        {
////            //修改开始
////            try {
////                response.sendRedirect("fore/login");
////            } catch (IOException e) {
////                e.printStackTrace();
////            }
////            //修
////        }
////        Long uid = order.getMemberId(); //用户的id
////        Address address1 = addressService.selectById(order.getAddressId());
////        String address = address1.adressToString();//用户的收货地址
////        String receiver = order.getShippingUser(); //收件人姓名
////        String mobile = address1.getReceiverMobile(); //收件人电话
//
//        //获取当前日期
//        SimpleDateFormat slm = new SimpleDateFormat("yyyy-MM-dd:HH:mm:ss");
//        String createDate = slm.format(new Date());
//        String orderCode = new SimpleDateFormat("yyyyMMdd").format(new Date()) + RandomUtils.nextInt(10000);
//
//        //更新订单状态---------------begin-----------------
////        String status = orderService.waitPay; //订单的状态
////        OrderStatus status = order.getOrderStatus();
//        Long s_oid = order.getId();
//        BigDecimal total = order.getPaymentMoney();
////        List<GoodsDetail> goodsDetailList = new ArrayList<GoodsDetail>();
////        List<OrderDetails> orderItemList= orderDetailsService.selectByOrderId(order.getId());
////        if(orderItemList!=null&orderItemList.size()>0) {
////            for (OrderDetails orderdetail : orderItemList) {
////                GoodsDetail goodsDetail = GoodsDetail.newInstance(String.valueOf(orderdetail.getOrderId()), orderdetail.getProductName(), orderdetail.getProductPrice().longValue(), orderdetail.getProductCnt());
////                goodsDetailList.add(goodsDetail);
////            }
////        }
////        String[] orderitem_idArr=request.getParameterValues("orderitem_id");
////        List<Integer> pidArr=new ArrayList();
////        List<Integer> shopidlist = new ArrayList<Integer>();
////        shopidlist = orderService.getaddcount(user.getId());
////        String flag = (String) session.getAttribute("isadd");
////        System.out.println("flag======================"+flag);
////        if(flag == "true"){
////            String moren = "0";
////            Integer t = orderService.addadd(address,post,receiver,mobile,moren,uid);
////        }
////        /*****************************修改如下**********************/
////        List<Integer> belonglist = new ArrayList<>();
////        /*********************************************************/
////
////
////        for(String oida:orderitem_idArr)
////        {
////            pidArr.add(orderService.getProductByid(Integer.parseInt(oida)).getId());
////            /*****************************修改如下**********************/
////            belonglist.add(orderService.getProductByid(Integer.parseInt(oida)).getBelong());
////            /*********************************************************/
////
////        }
////        int count = pidArr.size();
////        for(int i=0;i<count;i++)
////        {
////            boolean b = orderService.addOrder(orderCode, address, post, receiver, mobile, userMessage, createDate, uid, status, pidArr.get(i));
////            if (!b) {
////                throw new RuntimeException();
////            }
////        }
////        Integer[] oid = orderService.orderId_car(orderCode);//得到的是order_最左边的
////        int i=0;
////        for(Integer pid:pidArr)
////        {
////            orderService.updateOrderitem(oid[i],pid);//插入到orderitem的oid地方去
////            i++;
////        }
////        double total = (double) session.getAttribute("total");//总价（需要付款的金额）
////        System.out.println("从Session中取出 total:" + total);
////        model.addAttribute("total", total);
////        String s_oid="oid="+oid[0];
////        for(int j=1;j<oid.length;j++)
////        {
////            s_oid+="&oid="+oid[j];
////        }
////        model.addAttribute("oid", s_oid);
//        //更新订单状态---------------end-----------------
//
//        //--------------------------------------------------------------------------------------------------
//        String return_url="http://localhost:8004/order/paycallback?"+s_oid; //回调地址（付款成功后跳转的界面）
//        String notify_url = return_url;
//        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.openApiDomain, AlipayConfig.appid,
//                AlipayConfig.merchant_private_key, AlipayConfig.format, AlipayConfig.charset,
//                AlipayConfig.alipay_public_key, AlipayConfig.signType); // 获得初始化的AlipayClient
//        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();// 创建API对应的request
//
//        alipayRequest.setReturnUrl(return_url);
//
//        alipayRequest.setNotifyUrl(notify_url);// 在公共参数中设置回跳和通知地址
//        String message ="欢迎使用甄漂亮商城";//再支付界面显示的信息
//
//        alipayRequest.setBizContent("{" + "    \"out_trade_no\":\"" + s_oid + "\","
//                + "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," + "    \"total_amount\":\""
//                + total + "\"," + "    \"subject\":\"" + message + "\","
//                + "    \"body\":\"" + "遇到问题，请联系客服为你解答问题" + "\","
//                + "    \"passback_params\":\"merchantBizType%3d3C%26merchantBizNo%3d2016010101111\","
//                + "    \"extend_params\":{" + "    \"sys_service_provider_id\":\"2088511833207846\"" + "    }" + "  }");// 填充业务参数
//        String form = "";
//        try {
//            form = alipayClient.pageExecute(alipayRequest).getBody(); // 调用SDK生成表单
//        } catch (AlipayApiException e) {
//            e.printStackTrace();
//        }
//
//        try {
//            response.getWriter().write(form);// 直接将完整的表单html输出到页面
//            response.getWriter().flush();
//            response.getWriter().close();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//
//        //return "fore/alipay_car";
//    }

//    public Result PayCallback(@PathVariable Long id){
//        Order order = orderService.selectById(id);
//        order.setOrderStatus(OrderStatus.ZHI);
//        if (orderService.update(order)==true){
//            return Result.success("支付成功");
//        }else{
//            return Result.fail("支付失败");
//        }
//    }
}
